<?php
/**
 * Created by PhpStorm.
 * User: C。
 * Date: 2019/8/13
 * Time: 9:04
 */
namespace app\home\controller;

use think\Controller;
use think\Db;
use app\common\model\Config as ConfigModel;
use app\common\model\CompanyGongdengOrder as CompanyGongdengOrderModel;
use app\common\model\Company as CompanyModel;
use app\common\model\MemberLoginIp as MemberLoginIpModel;
/**
 * 登录控制器
 * Class Login
 * @package app\home\controller
 */
class Ceshi extends Controller
{
    public function sisi()
    {
        $param = input('param.');
        $arrContextOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
            ]
        ];
        $url = 'http://i.itpk.cn/api.php?api_key=63a4b519d4f14f1712c1a95631d675e2&api_secret=8jzwfat3u7g1&question='.$param['question'];
        $info = file_get_contents($url,false,stream_context_create($arrContextOptions));//发送HTTPs请求并获取返回的数据，推荐使用curl
//        $json = json_decode($info);//对json数据解码
//        $arr = get_object_vars($json);
//        $info = (array)$arr['data'];
//        $info = (array)$info['info'];
        $data['from_client_name'] = $param['username'];
        $data['content'] = $info;
        $data['type'] = 'say';
        $data['time'] = date('Y-m-d H:i:s');
        return admin_json(1,'获取成功',$data);
    }
    public function role()
    {
        $param = input('param.');
        $model = new CompanyModel;
        $cmodel = new CompanyGongdengOrderModel;
        $cmmodel = new ConfigModel;
        $price = $param['price']*100;
        $order = $cmodel->findData($param['orderid'],'id','comid,order_num,gongdeng,total_price');
        $order['order_num'] = date('Ymd') . time().str_pad(mt_rand(1, 99999), 5, '0');
        $data = $model->findData($order['comid'],'id','mch_id,much_secret,wx_appid,wx_secret,is_son');

        $weixinpay = new \WeixinPay\WeixinPay($data['wx_appid'],$param['openid'],$data['mch_id'],$data['much_secret'],$order['order_num'],$order['gongdeng'],$price,'JSAPI');
        $paydata = $weixinpay->pay();
        echo '<pre>';
        print_r($paydata);
    }
    public function getbook()
    {
        $xs_capter_list = [];
        $xs_content_list = [];
        set_time_limit(0);//0表示不限时

        $file = fopen('./2.txt', "r");

        $i = 0;//行数
        $j = 1; //章节数
        $content = '';
        $chaptertitle ='';
//输出文本中所有的行，直到文件结束为止。
        while(true) {
            if(feof($file)){
                //文章结尾
                if($content!='' && $chaptertitle!=''){
                    $content = strtr($content,["\r\n" => '<br>']);
//            $content = mb_substr($content,49);//去掉前49个广告字符
                    $xs_capter_list[$j]['content'] = $content;
                    //成功后
                    break;
                }
                break;
            }else{
                $now = fgets($file);
                $now = mb_convert_encoding($now,'UTF-8','UTF-8,GBK,GB2312,BIG5');//使用该函数对结果进行转码

                if(strpos($now,'$')!==FALSE && strpos($now,'$')!==FALSE){
                    //判断上一层循环
                    if($content!='' && $chaptertitle!=''){
                        //执行插入操作
                        $content = strtr($content,["\r\n" => '<br>']);
                        //$content = mb_substr($content,49);//去掉前49个广告字符
                        $xs_capter_list[$j]['content'] = $content;
                        //成功后
                        $content = '';
                        $chaptertitle = strtr($now,["\r\n" => '']);
                        $j++;
                    }else{
                        $chaptertitle = strtr($now,["\r\n" => '']);
                    }
                    $xs_capter_list[$j]['title'] = str_replace('$','',$chaptertitle);
                }else{
                    $content .= $now;
                }

            }

            $i++;
        }
        return $xs_capter_list;
    }
    /**
     * 微信模板消息测试
     * @param string $url 链接
     * @return bool|mixed
     */
    public function wechat()
    {
//        $openid = new Openid(config('home.zh_appid'),config('home.zh_secret'));
//        $user = $openid->auth_user();
//        echo '<pre>';
//        print_r($user);die;
//        echo 1;
        $wechat = new \WeChat\WeChat();
        $weiwei_token = $wechat->getToken(); // 获取微信token
        $data = $wechat::pushMessage([
            'openid' => 'ojnuYxC5WsMCVJX932L_XxhZRtcE', // 用户openid
            'access_token' => $weiwei_token,
            'template_id' => "PGjJ_29CKiFNhOUfj0xilLY_pWD_XnewaPsdJG0iiGg", // 填写你自己的消息模板ID
            'data' => [ // 模板消息内容，根据模板详情进行设置
                    'first'    => ['value' => urlencode("尊敬的@@@先生,感谢您对本次项目的善款！"),'color' => "#743A3A"],
                    'tradeDateTime' => ['value' => urlencode(date('Y-m-d H:i:s',time())),'color'=>'#173177'],
                    'tradeType' => ['value' => urlencode("余姚东临禅寺大雄宝殿吊顶缘启 一期"),'color'=>'#173177'],
                    'curAmount' => ['value' => urlencode("10,000,000元"),'color' => '#173177'],
                    'remark'   => ['value' => urlencode("福缘善庆，业缘除息。"),'color' => '#743A3A']
                ],
            'url' => 'https://www.cnblogs.com/' // 消息跳转链接
        ]);
        echo '<pre>';
        print_r($data);
    }
    public function output()
    {
        $data = Db::name('zhcheckin_mess')->field('id,name,sex,tel,is_ascetic,idcard,create_time,reside_day')->select();

        vendor("PHPExcel.PHPExcel");
        $excel = new \PHPExcel();
        //Excel表格式,这里简略写了4列
        $letter = array('A','B','C','D','E','F','G','H');
        //表头数组
        $tableheader = array('ID','姓名','性别','手机号','是否出家','身份证号','创建时间','入住天数');
        //填充表头信息
        for($i = 0;$i < count($tableheader);$i++) {
            $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
        }
        $excel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
        $excel->getActiveSheet()->getColumnDimension('B')->setWidth(10);
        $excel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $excel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        $excel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        //填充表格信息
        for ($i = 2;$i <= count($data) + 1;$i++) {
            $j = 0;
            foreach ($data[$i - 2] as $key=>$value) {
                if($key == 'sex'){
                    if($value == 1){
                        $value = '男';
                    }elseif($value == 2){
                        $value = '女';
                    }
                }
                if($key == 'create_time'){
                    $value = date('Y-m-d H:i:s',$value);
                }
                $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
                $j++;
            }
        }

        //创建Excel输入对象
        $write = new \PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="挂单记录.xls"');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');
    }
    public function calculator()
    {
        $ip = getIP();
        $address = getipaddress($ip);
        echo '<pre>';
        print_r($address);die;
        $date = date('Y-m-d H:i:s',time());
        Db::table('calculator_ip')->insert(['addtime'=>$date,'ip'=>$ip]);
        return 1;
    }

    public function cc()
    {
        $ip = getIP();
        $address = getipaddress($ip);
        $address = json_decode($address,true); //数据转换
        $ipmodel = new MemberLoginIpModel;
        $ipaddr = $ipmodel->findData('6583','mid');
        if(empty($ipaddr)){
            $ipmodel->addData(['mid'=>'6583','ip'=>$ip,'province'=>$address['content']['address_detail']['province'],'city'=>$address['content']['address_detail']['city'],'operator'=>1]);
        }else{
            $ipmodel->editData(['id'=>$ipaddr['id'],'ip'=>$ip,'province'=>$address['content']['address_detail']['province'],'city'=>$address['content']['address_detail']['city'],'operator'=>1]);
        }
        echo '<pre>';
        print_r($address);
    }

    function saveImageFromHttp($imgFromUrl){
        //取数组最后一个元素，得到文件类型
        $uploaddir = "wheader/";//设置文件保存目录 注意包含
        if (!file_exists($uploaddir)) {
            mkdir($uploaddir, 0755, true);
        }
        //得到 $imgFromUrl 的图片格式
        $ext = strrchr($imgFromUrl, ".");
        //如果图片格式不为.gif 或者.jpg .png，直接退出即可
        if ($ext != ".gif" && $ext != ".jpg" && $ext != 'png'){
            return false;
        }
        $newFileName = $uploaddir.date("dMYHis") . $ext;
        //用天月面时分秒来命名新的文件名

        ob_start();//打开输出
        readfile($imgFromUrl);//输出图片文件
        $img = ob_get_contents();//得到浏览器输出
        ob_end_clean();//清除输出并关闭
        //$size = strlen($img);//得到图片大小
        $fp2 = @fopen($newFileName, "a");
        fwrite($fp2, $img);//向当前目录写入图片文件，并重新命名
        fclose($fp2);
        return $newFileName;//返回新的文件名
    }

}